package com.zoffy.zoffyapi.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zoffy.apiclientsdk.client.ZoffyApiClient;
import com.zoffy.apiclientsdk.client.ZoffyClientFactory;
import com.zoffy.zoffyapi.commen.IdRequest;
import com.zoffy.zoffyapi.exception.BusinessException;
import com.zoffy.zoffyapi.exception.ErrorCode;

import com.zoffy.zoffyapi.model.dto.userInterfaceIngo.InvokeInterfaceRequest;
import com.zoffy.zoffyapi.model.vo.UserInterfaceVo;
import com.zoffy.zoffyapi.model.vo.UserVo;
import com.zoffy.zoffyapi.service.InterfaceInfoService;
import com.zoffy.zoffyapi.service.UserInterfaceInfoService;
import com.zoffy.zoffyapi.mapper.UserInterfaceInfoMapper;
import com.zoffy.zoffyapi.service.UserService;
import com.zoffy.zoffyapicommon.model.entity.InterfaceInfo;
import com.zoffy.zoffyapicommon.model.entity.User;
import com.zoffy.zoffyapicommon.model.entity.UserInterfaceInfo;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;

/**
* @author zoffy
* description 针对表【user_interface_info(用户调用接口关系)】的数据库操作Service实现
* createDate 2023-12-05 19:04:18
*/
@Service
public class UserInterfaceInfoServiceImpl extends ServiceImpl<UserInterfaceInfoMapper, UserInterfaceInfo>
    implements UserInterfaceInfoService{
    @Resource
    private ZoffyClientFactory zoffyClientFactory;
    @Resource
    private UserService userService;
    @Resource
    private UserInterfaceInfoMapper userInterfaceInfoMapper;
    @Resource
    private InterfaceInfoService interfaceInfoService;
    @Resource
    private Redisson redisson;
    public UserInterfaceInfo getUserInterfaceInfo(long userId,long interfaceId){
        QueryWrapper<UserInterfaceInfo> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        queryWrapper.eq("interface_info_id",interfaceId);
        return this.getOne(queryWrapper);
    }
    @Override
    public boolean grantInterface(HttpServletRequest request, IdRequest idRequest) {
        long interfaceId = idRequest.getId();
        if(interfaceId<=0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        UserVo userVo = userService.getCurrentUserVo(request);
        long userId = userVo.getId();
        UserInterfaceInfo oldUserInterfaceInfo=getUserInterfaceInfo(userId,interfaceId);

        RLock lock = redisson.getLock(String.format("interface_count_%s_%s",userId,interfaceId));
        lock.lock();
        try{
            UserInterfaceInfo userInterfaceInfo=new UserInterfaceInfo();
            //未申请过该接口
            if(oldUserInterfaceInfo==null){
                userInterfaceInfo.setUserId(userId);
                userInterfaceInfo.setInterfaceInfoId(interfaceId);
                userInterfaceInfo.setTotalNum(0);
                userInterfaceInfo.setLeftNum(100);
                userInterfaceInfo.setStatus(1);
                this.save(userInterfaceInfo);
                return true;
            }
            //已申请过该接口
            userInterfaceInfo.setId(oldUserInterfaceInfo.getId());
            Integer leftNum = oldUserInterfaceInfo.getLeftNum();
            userInterfaceInfo.setLeftNum(leftNum+100);
            this.updateById(userInterfaceInfo);
            return true;
        }finally {
            lock.unlock();
        }

    }

    @Override
    public List<UserInterfaceVo> listUserInterface(HttpServletRequest request) {
        UserVo userVo = userService.getCurrentUserVo(request);
        long userId = userVo.getId();
        return userInterfaceInfoMapper.getUSerInterfaceByUserId(userId);
    }

    @Override
    public String invokeInterface(HttpServletRequest request, InvokeInterfaceRequest invokeInterfaceRequest) {
        long interfaceId = invokeInterfaceRequest.getInterfaceId();
        String paramsString = invokeInterfaceRequest.getParams();

        User user = userService.getCurrentUser(request);
        String accessKey = user.getAccessKey();
        String secretKey = user.getSecretKey();
        HashMap params;
        try{
            params = JSON.parseObject(paramsString, HashMap.class);
        }catch (Exception e){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }


        InterfaceInfo interfaceInfo = interfaceInfoService.getById(interfaceId);
        String method = interfaceInfo.getMethod();

        ZoffyApiClient zoffyApiClient = zoffyClientFactory.createClient(String.valueOf(interfaceId));
        zoffyApiClient.setAccessKey(accessKey);
        zoffyApiClient.setSecretKey(secretKey);
        if("GET".equals(method)){
            return zoffyApiClient.get(params);
        }else if("POST".equals(method)){
            return zoffyApiClient.post(params);
        }

        return null;
    }
}




